const score = document.getElementById("score");
const player = document.getElementById("player");
const blockList = document.getElementById("blockList");

const startMask = document.getElementById("startMask");
const endMask = document.getElementById("endMask");
const resume = document.getElementById("resume");

const startBtn = document.getElementById("start");
const jumpBtn = document.getElementById("jump");
const resetBtn = document.getElementById("reset");

// 开始按钮标志
let startFlag = true;
// 初始化分数
let scoreNum = -2;
startBtn.addEventListener('click', function () {

  // 让开始游戏遮罩离开
  startMask.setAttribute("class", "startMaskLeave");
  if (startFlag) {
    // 让玩家动起来
    player.className = 'enter';
    setTimeout(() => {
      player.className = 'move';
    }, 1000);

    // 加障碍
    setInterval(function () {
      const block = document.createElement("div");
      block.setAttribute("id", "block");
      // 生成展示区block
      blockList.appendChild(block);
      // 获取相同id的block
      const allBlock = document.querySelectorAll("#block");
      // 展示区超过五个队首出队
      if (allBlock.length === 5) {
        allBlock[0].remove();
      }

      // 生成判断区block
      const collisionBlock = document.createElement("div");
      collisionBlock.setAttribute("id", "collisionBlock");
      // 生成展示区block
      blockList.appendChild(collisionBlock);
      // 判断区列表
      const collisionAllBlock = document.querySelectorAll("#collisionBlock");
      scoreNum = ++scoreNum;
      setInterval(function () {
        // 获取玩家的位置
        const playerRect = player.getBoundingClientRect();
        const playerTop = Math.floor(playerRect.top);
        const playerRight = Math.floor(playerRect.right);
        // 获取面对玩家的那个div的位置
        const blockRect = collisionAllBlock[0].getBoundingClientRect();
        const blockTop = Math.floor(blockRect.top);
        const blockLeft = Math.floor(blockRect.left);
        const isColliding = (playerRight - blockLeft > 50 && playerTop - blockTop < 212);
        // 经过了障碍
        if (isColliding) {
          // console.log(playerRight, blockLeft, playerTop, blockTop);
          if (playerTop - blockTop < 0 || blockTop === 0) {
            score.innerText = scoreNum;
          } else {
            // alert("没跳过障碍", window.location.reload());
            endMask.setAttribute("class", "endMaskCome");
            player.className = 'dead';
          }
          // 碰撞区队首出队
          collisionAllBlock[0].remove();
        }
      }, 200)
    }, 1000);
    startFlag = false;
  }
})

// 跳跃按钮
let jumpFlag = true;
jumpBtn.addEventListener('click', function () {
  // 限制隔800ms跳跃一次
  if (!jumpFlag) { return; }
  player.className = 'jump';
  jumpFlag = false;
  setTimeout(() => {
    player.className = 'move';
    jumpFlag = true;
  }, 800);
})

// 重新开始按钮
resetBtn.addEventListener('click', function () {
  window.location.reload();
})

// 继续按钮
resume.addEventListener('click', function () {
  window.location.reload();
})

